<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>手写call、bind、apply | Jaho’s Blog</title>
    <meta name="generator" content="VuePress 1.8.0">
    <link rel="icon" href="/favicon.ico">
    <link rel="manifest" href="/manifest.json">
    <meta name="description" content="记录日常学习工作">
    
    <link rel="preload" href="/assets/css/0.styles.5b8fe0a4.css" as="style"><link rel="preload" href="/assets/js/app.6514719e.js" as="script"><link rel="preload" href="/assets/js/2.ea114ffb.js" as="script"><link rel="preload" href="/assets/js/20.73fe0e75.js" as="script"><link rel="preload" href="/assets/js/4.e093c564.js" as="script"><link rel="prefetch" href="/assets/js/10.13203aa5.js"><link rel="prefetch" href="/assets/js/11.099868c4.js"><link rel="prefetch" href="/assets/js/12.c8365e17.js"><link rel="prefetch" href="/assets/js/13.89751e7c.js"><link rel="prefetch" href="/assets/js/14.31f563eb.js"><link rel="prefetch" href="/assets/js/15.08b381b6.js"><link rel="prefetch" href="/assets/js/16.1a3867de.js"><link rel="prefetch" href="/assets/js/17.7dd4e0c6.js"><link rel="prefetch" href="/assets/js/18.907c4597.js"><link rel="prefetch" href="/assets/js/19.fac8aa1a.js"><link rel="prefetch" href="/assets/js/21.5c50aa1c.js"><link rel="prefetch" href="/assets/js/22.83d03663.js"><link rel="prefetch" href="/assets/js/23.061e7ac0.js"><link rel="prefetch" href="/assets/js/24.cc7e9011.js"><link rel="prefetch" href="/assets/js/25.fa6c7aef.js"><link rel="prefetch" href="/assets/js/26.39392f70.js"><link rel="prefetch" href="/assets/js/27.204436be.js"><link rel="prefetch" href="/assets/js/28.3f54c157.js"><link rel="prefetch" href="/assets/js/29.799d048c.js"><link rel="prefetch" href="/assets/js/3.6c5d6214.js"><link rel="prefetch" href="/assets/js/30.deed02f3.js"><link rel="prefetch" href="/assets/js/31.5916873b.js"><link rel="prefetch" href="/assets/js/32.b0634144.js"><link rel="prefetch" href="/assets/js/33.734675b8.js"><link rel="prefetch" href="/assets/js/34.20404dc4.js"><link rel="prefetch" href="/assets/js/35.d93b829f.js"><link rel="prefetch" href="/assets/js/36.b0692d8d.js"><link rel="prefetch" href="/assets/js/37.3dffa306.js"><link rel="prefetch" href="/assets/js/38.04649a97.js"><link rel="prefetch" href="/assets/js/39.7dfcdc32.js"><link rel="prefetch" href="/assets/js/40.04914511.js"><link rel="prefetch" href="/assets/js/41.ced85449.js"><link rel="prefetch" href="/assets/js/42.72739213.js"><link rel="prefetch" href="/assets/js/43.de1cff16.js"><link rel="prefetch" href="/assets/js/44.48e301ae.js"><link rel="prefetch" href="/assets/js/45.870a7650.js"><link rel="prefetch" href="/assets/js/46.657f15b8.js"><link rel="prefetch" href="/assets/js/47.3df1bfdb.js"><link rel="prefetch" href="/assets/js/48.f4e4e774.js"><link rel="prefetch" href="/assets/js/49.632bf611.js"><link rel="prefetch" href="/assets/js/5.6531e181.js"><link rel="prefetch" href="/assets/js/50.a8018493.js"><link rel="prefetch" href="/assets/js/51.cb424f59.js"><link rel="prefetch" href="/assets/js/52.a9f595dc.js"><link rel="prefetch" href="/assets/js/53.cf8a9ec0.js"><link rel="prefetch" href="/assets/js/54.46d774a3.js"><link rel="prefetch" href="/assets/js/55.3574f9b8.js"><link rel="prefetch" href="/assets/js/56.baf60ba5.js"><link rel="prefetch" href="/assets/js/57.af42b559.js"><link rel="prefetch" href="/assets/js/58.9300cb59.js"><link rel="prefetch" href="/assets/js/6.00f437ec.js"><link rel="prefetch" href="/assets/js/7.58ac7166.js"><link rel="prefetch" href="/assets/js/8.1b9c5002.js"><link rel="prefetch" href="/assets/js/9.5c076362.js">
    <link rel="stylesheet" href="/assets/css/0.styles.5b8fe0a4.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="Jaho’s Blog" class="logo"> <span class="site-name can-hide">Jaho’s Blog</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/posts/" class="nav-link router-link-active">
  技术博客
</a></div> <a href="https://juejin.cn/user/26836627369806" target="_blank" rel="noopener noreferrer" class="repo-link">
    个人主页
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/posts/" class="nav-link router-link-active">
  技术博客
</a></div> <a href="https://juejin.cn/user/26836627369806" target="_blank" rel="noopener noreferrer" class="repo-link">
    个人主页
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><a href="/posts/" aria-current="page" class="sidebar-link">写在前面</a></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>工作问题解决</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>JavaScript</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/posts/JavaScript/闭包作用域.html" class="sidebar-link">了解闭包及作用域</a></li><li><a href="/posts/JavaScript/短路原则.html" class="sidebar-link">布尔判定和短路原则</a></li><li><a href="/posts/JavaScript/类型转换.html" class="sidebar-link">类型转换</a></li><li><a href="/posts/JavaScript/数组转树.html" class="sidebar-link">数组转树方案</a></li><li><a href="/posts/JavaScript/数组拍平.html" class="sidebar-link">数组拍平方案</a></li><li><a href="/posts/JavaScript/数组求和.html" class="sidebar-link">数组求和（不允许使用循环）</a></li><li><a href="/posts/JavaScript/async.html" class="sidebar-link">async await实战</a></li><li><a href="/posts/JavaScript/defer.html" class="sidebar-link">JS文档的解析:async、defer 属性</a></li><li><a href="/posts/JavaScript/set.html" class="sidebar-link">Set笔记</a></li><li><a href="/posts/JavaScript/map.html" class="sidebar-link">Map笔记</a></li><li><a href="/posts/JavaScript/call.html" aria-current="page" class="active sidebar-link">手写call、bind、apply</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/posts/JavaScript/call.html#call的实现" class="sidebar-link">call的实现</a></li><li class="sidebar-sub-header"><a href="/posts/JavaScript/call.html#手写call" class="sidebar-link">手写call</a></li><li class="sidebar-sub-header"><a href="/posts/JavaScript/call.html#手写apply" class="sidebar-link">手写apply</a></li><li class="sidebar-sub-header"><a href="/posts/JavaScript/call.html#手写bind" class="sidebar-link">手写bind</a></li></ul></li><li><a href="/posts/JavaScript/eventBus.html" class="sidebar-link">Eventbus使用</a></li><li><a href="/posts/JavaScript/instanceof.html" class="sidebar-link">浅析instanceof的实现</a></li><li><a href="/posts/JavaScript/function.html" class="sidebar-link">如何优雅的用function实现一个class</a></li><li><a href="/posts/JavaScript/require.html" class="sidebar-link">浅析commonjs中require的执行方式</a></li><li><a href="/posts/JavaScript/promise.html" class="sidebar-link">手写Promise</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Css</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Nodejs</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Vue</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Git</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="手写call、bind、apply"><a href="#手写call、bind、apply" class="header-anchor">#</a> 手写call、bind、apply</h1> <blockquote><p>call apply bind 的实现的面试中几乎必定出现的一些内容，今天来用一篇文章整理一下这里的内容，加深一下JS基础知识体系。同时文章也被收录到我的《JS基础》专栏中，欢迎大家点击收藏加关注。</p></blockquote> <h2 id="call的实现"><a href="#call的实现" class="header-anchor">#</a> call的实现</h2> <blockquote><p><strong><code>call()</code></strong>  方法使用一个指定的 <code>this</code> 值和单独给出的一个或多个参数来调用一个函数。</p></blockquote> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token literal-property property">name</span><span class="token operator">:</span><span class="token string">'plus'</span><span class="token punctuation">}</span>
<span class="token keyword">function</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token parameter">a</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token operator">+</span><span class="token string">'_'</span><span class="token operator">+</span>a<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token function">getName</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span><span class="token string">'666'</span><span class="token punctuation">)</span> <span class="token comment">//plus_666</span>
</code></pre></div><p>以上的call可以换成用函数的隐式绑定调用的方法来使用 比如</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">name</span><span class="token operator">:</span><span class="token string">'plus'</span><span class="token punctuation">,</span>
    <span class="token function-variable function">getName</span><span class="token operator">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">a</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token operator">+</span><span class="token string">'_'</span><span class="token operator">+</span>a<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
obj<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token string">'666'</span><span class="token punctuation">)</span> <span class="token comment">//plus_666</span>
</code></pre></div><p>把函数放到要指向的对象中，通过<code>obj.</code>的隐式调用，就能够改变this的指向</p> <p>那么根据这个调用方法我们就有思路来实现我们的call方法了</p> <h2 id="手写call"><a href="#手写call" class="header-anchor">#</a> 手写call</h2> <ul><li>1.在对象中声明一个临时函数，将要执行的函数放到其中</li> <li>2.通过隐式调用</li> <li>3.删除临时函数</li> <li>4.判断传入对象是否为空</li></ul> <div class="language-js extra-class"><pre class="language-js"><code>
<span class="token function">_call</span><span class="token punctuation">(</span>fn<span class="token punctuation">,</span><span class="token operator">...</span>arg<span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
     <span class="token keyword">if</span><span class="token punctuation">(</span>obj<span class="token operator">===</span><span class="token keyword">null</span><span class="token operator">||</span>obj<span class="token operator">===</span><span class="token keyword">undefined</span><span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token comment">//没有指定对象时候</span>
         obj <span class="token operator">=</span>  window
     <span class="token punctuation">}</span>
    obj<span class="token punctuation">.</span>temp <span class="token operator">=</span> fn <span class="token comment">//临时函数</span>
    <span class="token keyword">let</span> res <span class="token operator">=</span> obj<span class="token punctuation">.</span><span class="token function">temp</span><span class="token punctuation">(</span><span class="token operator">...</span>arg<span class="token punctuation">)</span>
    <span class="token keyword">delete</span> obj<span class="token punctuation">.</span>temp <span class="token comment">//临时函数完成它的任务就要消失了</span>
    <span class="token keyword">return</span> res
<span class="token punctuation">}</span>

<span class="token comment">//改进版</span>
<span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">_call</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span><span class="token operator">...</span>arg</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    obj <span class="token operator">=</span> obj <span class="token operator">||</span> window <span class="token comment">//没有指定对象时候 指向window</span>
    <span class="token keyword">const</span> temp <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">//小技巧，Symbol可以用来声明一个对象的属性</span>
    obj<span class="token punctuation">.</span>temp <span class="token operator">=</span> <span class="token keyword">this</span> <span class="token comment">//因为call的声明方法是`Function.prototype._call`所以this就是要调用的函数</span>
    <span class="token keyword">let</span> res <span class="token operator">=</span> obj<span class="token punctuation">.</span><span class="token function">temp</span><span class="token punctuation">(</span><span class="token operator">...</span>arg<span class="token punctuation">)</span>
    <span class="token keyword">delete</span> obj<span class="token punctuation">.</span>temp
    <span class="token keyword">return</span> res
<span class="token punctuation">}</span>
</code></pre></div><h2 id="手写apply"><a href="#手写apply" class="header-anchor">#</a> 手写apply</h2> <blockquote><p>apply的实现基本是和call是差不多的，有区别的一点是对于传入的参数，call接收的是多个参数，apply接收的是一个参数数组</p></blockquote> <div class="language-diff extra-class"><pre class="language-diff"><code>
<span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line"> Function.prototype.apply = function(obj,...arg){
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line"> Function.prototype.apply = function(obj,arg){
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   obj = obj || window //没有指定对象时候 指向window
</span><span class="token prefix unchanged"> </span><span class="token line">   const temp = Symbol() //小技巧，Symbol可以用来声明一个对象的属性
</span><span class="token prefix unchanged"> </span><span class="token line">   obj.temp = this //因为call的声明方法是`Function.prototype._call`所以this就是要调用的函数
</span><span class="token prefix unchanged"> </span><span class="token line">   let res = obj.temp(...arg)
</span><span class="token prefix unchanged"> </span><span class="token line">   delete obj.temp
</span><span class="token prefix unchanged"> </span><span class="token line">   return res
</span></span>}
</code></pre></div><h2 id="手写bind"><a href="#手写bind" class="header-anchor">#</a> 手写bind</h2> <blockquote><p>bind的实现与call和apply的有点不同，bing中返回的是一个函数，需要对函数进行第二次调用才能真正的执行到函数。我们先来看一下例子。</p></blockquote> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">function</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token parameter">a<span class="token punctuation">,</span>b<span class="token punctuation">,</span>c<span class="token punctuation">,</span>d</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>a<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>b<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>c<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>d<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token keyword">let</span> b1 <span class="token operator">=</span> <span class="token function">getName</span><span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span>
<span class="token function">b1</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">)</span>
</code></pre></div><p>我们可以看到bind的最终调用是分两次实现的，这个实现类似于是柯里化的实现，那么看了bin的使用后我们就可以来手动写出bind了</p> <p>步骤分为几步：</p> <ul><li>函数中返回一个函数</li> <li>还是和call、apply函数一样设置一个临时函数</li> <li>在返回的函数中，因为是最后一次执行，将所有参数传入，比如arg1传入的是1、2，arg2传入的是3、4。</li></ul> <div class="language-js extra-class"><pre class="language-js"><code><span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">_bind</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span><span class="token operator">...</span>arg1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    obj <span class="token operator">=</span> obj <span class="token operator">||</span> window
    <span class="token keyword">const</span> temp <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    obj<span class="token punctuation">[</span>temp<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">this</span>
    <span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter"><span class="token operator">...</span>arg2</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        obj<span class="token punctuation">[</span>temp<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token operator">...</span>arg1<span class="token punctuation">,</span><span class="token operator">...</span>arg2<span class="token punctuation">)</span> <span class="token comment">//obj[temp](1,2,3,4)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p><em><strong>本文正在参加<a href="https://juejin.cn/post/7162096952883019783" title="https://juejin.cn/post/7162096952883019783" target="_blank" rel="noopener noreferrer">「金石计划 . 瓜分6万现金大奖」<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></strong></em></p></div> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">上次更新:</span> <span class="time">2023-01-04 10:56:12</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
      ←
      <a href="/posts/JavaScript/map.html" class="prev">
        Map笔记
      </a></span> <span class="next"><a href="/posts/JavaScript/eventBus.html">
        Eventbus使用
      </a>
      →
    </span></p></div> </main></div><div class="global-ui"><!----><!----></div></div>
    <script src="/assets/js/app.6514719e.js" defer></script><script src="/assets/js/2.ea114ffb.js" defer></script><script src="/assets/js/20.73fe0e75.js" defer></script><script src="/assets/js/4.e093c564.js" defer></script>
  </body>
</html>
